package com.hucc.redislock.command;

import com.hucc.redislock.RedisLockContext;
import com.hucc.redislock.result.CommandResult;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.lang.Boolean;

public class RenewExpirationRedisCommand extends AbstractRedisCommand {

    public RenewExpirationRedisCommand(String lockName, String threadName) {
        super(lockName, threadName);
    }

    @Override
    public CommandResult<Boolean> execute() {
        String script =
                "if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
                    "redis.call('pexpire', KEYS[1], ARGV[1]); " +
                    "return 1; " +
                "end; " +
                "return 0;";

        List<String> keys = new ArrayList<String>();
        keys.add(lockName);

        List<String> args = new ArrayList<String>();
        args.add(String.valueOf(RedisLockContext.getRedisLockConfig().getLockWatchdogTimeout()));
        args.add(threadName);

        Long evalResult = (Long) executeScript(script, keys, args);

        CommandResult<Boolean> commandResult = new CommandResult<Boolean>();
        commandResult.setSuccess(evalResult == 1);
        return commandResult;
    }
}
